const db = require('../../db')
const bcryptjs = require('bcryptjs')
module.exports = {
  //获取用户信息
  getUserInfo(req, res) {
    db.query(`select * from user where id = ?`, req.auth.id, (err, resList) => {
      if (err) {
        return res.ms(err)
      }

      const userInfo = { ...resList[0], password: undefined }
      return res.ms('ok', 0, userInfo)
    })
  },
  //更新用户信息
  updateUserInfo(req, res) {
    console.log(req.body)
    db.query(
      `update user set ? where id = ?`,
      [req.body, req.body.id],
      (err, resList) => {
        if (err) {
          res.ms(err)
        } else if (resList.affectedRows != 1) {
          res.ms('更新失败')
        } else {
          res.ms('ok', 0)
        }
      }
    )
  },
  //更新密码
  updatePwd(req, res) {
    //判断用户是否存在
    db.query(`select * from user where id = ?`, req.auth.id, (err, resList) => {
      if (err) {
        res.ms(err)
      } else if (resList.length != 1) {
        res.ms('修改密码失败')
      } else {
        //判断老密码是否正确

        if (bcryptjs.compareSync(req.body.oldPwd, resList[0].password)) {
          //加密新密码并保存
          const newstr = bcryptjs.hashSync(req.body.newPwd)
          db.query(
            `update user set password=? where id = ?`,
            [newstr, req.auth.id],
            (err, resList) => {
              if (err) {
                res.ms(err)
              } else if (resList.affectedRows != 1) {
                res.ms('修改密码失败')
              } else {
                res.ms('ok', 0)
              }
            }
          )
        } else {
          res.ms('旧密码错误')
        }
      }
    })
  },
  //更新头像
  updateAva(req, res) {
    db.query(`select * from user where id = ?`, req.auth.id, (err, resList) => {
      if (err) {
        res.ms(err)
      } else if (resList.length != 1) {
        res.ms('用户id不唯一')
      } else {
        db.query(
          `update user set user_pic = ? where id = ?`,
          [req.body.avatar, req.auth.id],
          (err, dbRes) => {
            if (err) {
              res.ms(err)
            } else {
              res.ms('ok', 0)
            }
          }
        )
      }
    })
  }
}
